package com.pricetag.iqengine;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import com.pricetag.helpers.Constants;

public class IQEngineResultStore {

	private static String latestQueryID = null;
	private static Map<String, String> results = new HashMap<String, String>();
	private static LinkedList<String> readyQueue = new LinkedList<String>();
	private static Map<String, String> iqeToSearchRecordIDMap = new HashMap<String, String>();

	public static void addQueryID(String queryID, String pathName) {
		synchronized (results) {
			results.put(queryID, null);
			latestQueryID = queryID;
		}
		File imageFile = new File(pathName);
		String imageFilename = imageFile.getName();
		int indexOfDot = imageFilename.indexOf(".image");
		String searchRecordID = imageFilename.substring(0, indexOfDot);
		synchronized (iqeToSearchRecordIDMap) {
			iqeToSearchRecordIDMap.put(queryID, searchRecordID);
		}
		
	}

	public static void putResult(String queryID, String result) {
		if (!results.containsKey(queryID)) {
			return;
		}
		synchronized (results) {
			results.put(queryID, result);
			readyQueue.addLast(queryID);
		}
	}

	public static void markNoMatch(String queryID) {
		if (!results.containsKey(queryID)) {
			return;
		}
		synchronized (results) {
			results.put(queryID, Constants.NO_MATCH_STRING);
			readyQueue.addLast(queryID);
		}
	}
	
	public static Map<String, String> getReadyResults() {
		Map<String, String> map = new HashMap<String, String>();
		String queryID, result, searchRecordID;
		synchronized(results) {
			while (!readyQueue.isEmpty()) {
				queryID = readyQueue.pop();
				result = results.get(queryID);
				results.remove(queryID);
				searchRecordID = iqeToSearchRecordIDMap.get(queryID);				
				map.put(searchRecordID, result);
			}		
		}
		synchronized(iqeToSearchRecordIDMap) {
			for (String tempQueryID : map.keySet()) {
				iqeToSearchRecordIDMap.remove(tempQueryID);
			}
		}
		return map;
	}
	
	public static String getLatestQueryID() {
		return latestQueryID;
	}
	
	public static boolean hasMoreLeft() {
		return results.size() > 0;
	}
	
	public static void clearStore() {		
		results = new HashMap<String, String>();
		readyQueue = new LinkedList<String>();
		latestQueryID = null;		
	}

}
